<template>
  <div class="app-container">
    <el-form class="searchForm" :inline="true" :model="queryForm" label-width="90px">
      <el-form-item label="名称">
        <el-input v-model="queryForm.rolename"> </el-input>
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="queryForm.roletype" style="width: 170px" placeholder="请选择" clearable>
          <el-option label="菜单" value="1"> 菜单 </el-option>
          <el-option label="数据" value="2"> 数据 </el-option>
          <el-option label="功能" value="3"> 功能 </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="info" @click="pageChange(1)">查询</el-button>
        <el-button type="info" @click="onAdd">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="tableData"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      height="600"
      stripe
      border
      style="width: 100%"
    >
      <el-table-column :resizable="false" label="操作" width="150" fixed>
        <template slot-scope="scope">
          <span class="edit-tooltip">
            <el-tooltip effect="dark" content="删除" placement="bottom">
              <el-button type="text" @click="onDelete(scope.row)">
                <svg-icon style="fill: #ff4e1d" icon-class="butongyi"></svg-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="修改" placement="bottom">
              <el-button type="text" @click="onEdit(scope.row)">
                <svg-icon style="fill: #ff4e1d" icon-class="a-xiugai"></svg-icon>
              </el-button>
            </el-tooltip>
            <!-- <el-tooltip effect="dark" content="分配菜单" placement="bottom"> -->
            <el-link style="margin-left: 5px" type="success" @click="onClickMenu(scope.row)"> 分配菜单 </el-link>
            <!-- </el-tooltip> -->
          </span>
        </template>
      </el-table-column>
      <el-table-column :resizable="false" prop="rolename" label="名称" min-width="120" />
      <el-table-column :resizable="false" prop="roletypestr" label="类型" min-width="180" />
    </el-table>
    <el-pagination
      style="margin: 10px"
      :current-page="queryForm.pagenum"
      :page-sizes="[20, 50, 100]"
      :page-size="queryForm.pagesize"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="sizeChange"
      @current-change="pageChange"
    />
    <el-dialog
      destroy-on-close
      :title="title"
      :visible.sync="visible"
      :close-on-click-modal="false"
      width="600px"
      @close="onClose"
    >
      <span>
        <el-form ref="form" :model="form" :rules="formRules" label-width="100px" :inline="false">
          <el-form-item label="名称" prop="rolename">
            <el-input v-model="form.rolename" />
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="form.roletype" style="width: 170px" placeholder="请选择" clearable>
              <el-option label="菜单" :value="1"> 菜单 </el-option>
              <el-option label="数据" :value="2"> 数据 </el-option>
              <el-option label="功能" :value="3"> 功能 </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </span>
      <div slot="footer">
        <el-button type="info" @click="onSubmit">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="分配菜单" :visible.sync="visible2" width="800px" @close="onClose">
      <span>
        <el-tree
          ref="tree"
          class="tree"
          default-expand-all
          check-strictly
          show-checkbox
          :expand-on-click-node="false"
          node-key="id"
          :data="data"
          :default-checked-keys="defaultCheckedKeys"
          :props="defaultProps"
          @check="checkChange"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span>
              <svg-icon
                style="font-size: 18px"
                :icon-class="node.childNodes.length > 0 ? 'wenjianjia' : 'a-shebei'"
              ></svg-icon>
              {{ data.menuname }}
            </span>
          </span>
        </el-tree>
      </span>
      <span slot="footer">
        <el-button type="info" @click="onSubmitTree">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { QueryPageList, Save, Del, RoleMenuArr, setRoleMenus } from '@/api/settings/juese'
import { QueryList } from '@/api/settings/caidan'
export default {
  name: 'Juese',
  data() {
    return {
      queryForm: {
        rolename: '',
        roletype: '',
        parentid: '',
        pagenum: 1,
        pagesize: 20,
        isneed: ''
      },
      tableData: [],
      total: 0,
      loading: true,
      visible: false,
      title: '角色管理',
      formRules: {
        code: [{ required: true, message: '请输入编号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }]
      },
      form: {
        id: 0,
        rolename: '',
        roletype: ''
      },
      visible2: false,
      data: [],
      check: { roleid: '', menuidarr: '' },
      defaultCheckedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'menuname'
      }
    }
  },
  created() {
    this.onSearch()
  },
  methods: {
    sizeChange(size) {
      this.queryForm.pagesize = size
      this.onSearch()
    },
    pageChange(page) {
      this.queryForm.pagenum = page
      this.onSearch()
    },
    onSearch() {
      this.loading = true
      QueryPageList(this.queryForm)
        .then(result => {
          if (result.success) {
            var content = result.content || []
            this.total = content.total
            this.tableData = content.list
          } else {
            this.$message.error(result.message)
          }
          this.loading = false
        })
        .catch(err => {
          console.log(err)
          this.loading = false
        })
    },
    onEdit(data) {
      this.form = {
        id: data.id,
        rolename: data.rolename,
        roletype: data.roletype
      }
      this.visible = true
    },
    checkChange(data, checked) {
      console.log(data, checked)
      this.check.menuidarr = [...checked.halfCheckedKeys, ...checked.checkedKeys].join(',')
    },
    // 树状结构数据转换
    turnData(arr, pid) {
      const res = []
      arr.forEach(item => {
        if (item.parentid == pid) {
          const children = this.turnData(arr, item.id)
          if (children.length > 0) {
            item.children = children
          }
          res.push(item)
        }
      })
      return res
    },
    async getTree() {
      const { content } = await QueryList({})
      console.log('content', content)
      const result = this.turnData(content, '0')
      this.data = result
      // QueryList({})
      //   .then(result => {
      //     if (result.success) {
      //       var content = result.content || []
      //       console.log('content', content)
      //       var data = this.$handleTree(content, 'id', 'parentid', 'children')
      //       this.data = data
      //     }
      //   })
      //   .catch(err => {
      //     console.log(err)
      //   })
    },
    onClickMenu(data) {
      this.getTree()
      this.check.roleid = data.id
      RoleMenuArr({ id: data.id }).then(result => {
        console.log('根据id查询已有菜单', result)
        if (result.success) {
          var list = result.content
          if (list) {
            var arr = list.menuidarr.split(',')
            this.defaultCheckedKeys = arr
            this.check.menuidarr = list.menuidarr
          } else {
            this.defaultCheckedKeys = []
            this.check.menuidarr = ''
          }

          console.log(this.defaultCheckedKeys)
          this.visible2 = true
        } else {
          this.$message.error(result.message)
        }
      })
    },
    onDelete(data) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          Del({ id: data.id }).then(result => {
            if (result.success) {
              this.onSearch()
              return this.$message.success('删除成功')
            } else {
              return this.$message.error(result.message)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    onAdd() {
      this.form.id = 0
      this.visible = true
    },
    onClose() {
      this.data = []
      this.defaultCheckedKeys = []
      this.check = { roleid: '', menuidarr: '' }
      this.form = {
        id: 0,
        rolename: '',
        roletype: ''
      }
    },
    onSubmitTree() {
      console.log(this.check)
      setRoleMenus(this.check)
        .then(result => {
          if (result.success) {
            this.$message.success('设置成功')
            this.visible2 = false
            this.$store.dispatch('user/getUserMenu')
          } else {
            return this.$message.error(result.message)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          Save(this.form)
            .then(result => {
              if (result.success) {
                this.$message.success('添加成功')
                this.visible = false
                this.onSearch()
              } else {
                return this.$message.error(result.message)
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  height: 30px;
  line-height: 30px;
  background: rgba(0, 0, 0, 0.3);
  font-size: 14px;
  text-transform: uppercase;
  margin: 0 0 5px;
  padding: 0 10px;
  display: inline-block;
  letter-spacing: 0.5px;
}

.tree {
  height: 500px;
  overflow-y: auto;
}

.el-select {
  width: 100% !important;
}
</style>
